import { RouteGuard } from '@/components/index.jsx';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import 'dayjs/locale/zh-cn';
import { Routers } from '@/router/index.jsx';
import { useLocation, useNavigate } from 'react-router-dom';
import { setNavigate } from '@/utils/navigate.js';
import { setLocation } from '@/utils/location.js';
import GlobalSpin from '@/components/GlobalSpin/index.jsx';
import { useEffect } from 'react';
import { createVersionPolling } from 'version-polling';

function App() {
  useEffect(() => {
    createVersionPolling({
      appETagKey: '__APP_ETAG__',
      pollingInterval: 5 * 1000, // 单位为毫秒
      silent: process.env.NODE_ENV === 'development', // 开发环境下不检测
      onUpdate: (self) => {
        // 当检测到有新版本时，执行的回调函数，可以在这里提示用户刷新页面
        const result = confirm('页面有更新，点击确定刷新页面！');
        if (result) {
          self.onRefresh();
        } else {
          self.onCancel();
        }
      }
    });
  }, []);

  return (
    <ConfigProvider
      locale={zhCN}
      theme={{
        cssVar: true,
        hashed: false,
        token: {
          fontFamily: "'HarmonyOS_Regular', system-ui"
        }
      }}
    >
      <GlobalSpin />
      <FunctionRegistry>
        <RouteGuard>
          <Routers />
        </RouteGuard>
      </FunctionRegistry>
    </ConfigProvider>
  );
}

// 函数注册
function FunctionRegistry({ children }) {
  const navigate = useNavigate();
  const location = useLocation();
  setNavigate(navigate);
  setLocation(location);
  return children;
}

export default App;
